<?php

namespace app\admin\controller\consumable;

use app\common\controller\Backend;
use think\Db;
use think\Session;
/**
 * 耗材管理
 *
 * @icon fa fa-circle-o
 */
class Consumable extends Backend
{

    /**
     * Consumable模型对象
     * @var \app\admin\model\consumable\Consumable
     */
    protected $model = null;
    protected $shop_model = null;
    protected $consumable_shop_model = null;
    //当前店铺id
    protected $curr_shop_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\consumable\Consumable;
        $this->shop_model = new \app\admin\model\wanlshop\Shop;
        $this->consumable_shop_model = new \app\admin\model\wanlshop\ConsumableShop;
        //当前店铺id
        $this->curr_shop_id = Session::get('shop');
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //当前管理员店铺id 
        $_admin = Session::get('adminshop');

        //当前店铺id
        $shop_id = Session::get('shop');

        //是否显示tab
        $show_tab = 0;

        //是否显示copy
        $show_copy = 0;

        if($_admin == $shop_id && $shop_id != 1){
            $show_tab = 1;
        }

        if($_admin == $shop_id && $shop_id == 1){
            $show_copy = 1;
        }

        $conditions = ['shop_id'=>$shop_id];

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->where($conditions)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->paginate($limit);

            $rows = $list->items();

            $total = $list->total();

            if ($total > 0) {
                foreach ($rows as $key => &$value) {
                    $value['show_copy'] = $show_copy;
                }
            }

            $result = ['total' => $total, 'rows' => $rows,'show_tab'=>$show_tab];
            return json($result);
        }

        $this->view->assign('show_tab',$show_tab);
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['shop_id'] = $this->curr_shop_id;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 上架
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function listing($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        $params = [
            'status' => 1
        ];
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

     /**
     * 下架
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function delist($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        $params = [
            'status' => 0
        ];
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function resubmit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $ids = $this->request->get('ids');
            if (empty($ids)) {
                return json([]);
            }

            //查询已复制过当前商品的店铺
            $shop_ids = $this->consumable_shop_model->where('consumable_id',$ids)->column('shop_id');
            $shop_ids[] = 1;
            $shop_ids = array_unique($shop_ids);
            $conditions = [];
            $conditions['id'] = ['not in',$shop_ids];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->count();

            $list = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->assignConfig("goods_id", $ids);
        return $this->view->fetch();
    }

    public function savegoodsshop()
    {
        // 'ids'=>[12,2,1],'goods_id'=>27
        if ($this->request->isAjax()) {

            $params = $this->request->post();
            if (!isset($params['ids']) || empty($params['ids']) || !isset($params['goods_id']) || empty($params['goods_id'])) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $shop_ids = $params['ids'];
            $consumable_id = $params['goods_id'];
            //查询信息
            $goods_info = $this->model->get($consumable_id)->toArray();
            if (empty($goods_info)) {
                $this->error(__('No Results were found'));
            }
            
            Db::startTrans();
            try {
                $goods_data = $goods_info;
                unset($goods_data['id']);
                unset($goods_data['status_text']);

                if (count($shop_ids) > 0) {
                    foreach ($shop_ids as $k_shop => $v_shop) {
                        if ($goods_info['shop_id'] == $v_shop) {
                            continue;
                        }
                        //处理新的商品
                        $goods_data['shop_id'] = $v_shop;

                        // print_r($goods_data);die;
                        $new_goods = $this->model->insert($goods_data);


                        if (empty($new_goods)) {
                            Db::rollback();
                            $this->error('操作失败！请稍后重试');
                        }

                        $new_consumable_id = $this->model->getLastInsID();

                        //保存商品铺设记录
                        $insert_data = [];
                        $insert_data['shop_id'] = $v_shop;
                        $insert_data['consumable_id'] = $consumable_id;
                        $insert_data['new_consumable_id'] = $new_consumable_id;
                        $insert_data['createtime'] = time();
                        $insert_res = $this->consumable_shop_model->insert($insert_data);
                        if (empty($insert_res)) {
                            Db::rollback();
                            $this->error('操作失败！请稍后重试');
                        }
                    }
                }

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }
        $this->error(__('You have no permission', ''));
    }

    public function topgoods()
    {
        //当前管理员店铺id 
        $_admin = Session::get('adminshop');

        //当前店铺id
        $shop_id = Session::get('shop');

        $cur_shop_id = 1;

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('shop_id', '=', $cur_shop_id)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('shop_id', '=', $cur_shop_id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            if ($total > 0) {
                foreach ($list as $key => &$value) {
                    $value['already_copy'] = 0;
                    $exist = $this->consumable_shop_model->where(['consumable_id'=>$value['id'],'shop_id'=>$shop_id])->find();
                    if ($exist && !empty($exist)) {
                        $value['already_copy'] = 1;
                    }
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function resubmittoshop($ids = null)
    {
        // 'ids'=>[12,2,1],'goods_id'=>27
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }

            //当前店铺id
            $shop_id = Session::get('shop');

            $exist = $this->consumable_shop_model->where(['consumable_id'=>$ids,'shop_id'=>$shop_id])->find();
            if ($exist && !empty($exist)) {
                $this->error(__('当前商品已经添加过了！'));
            }

            $shop_ids = [$shop_id];
            $consumable_id = $ids;
            //查询商品信息
            $goods_info = $this->model->get($consumable_id)->toArray();
            if (empty($goods_info)) {
                $this->error(__('No Results were found'));
            }
            
            Db::startTrans();
            try {
                $goods_data = $goods_info;
                unset($goods_data['id']);
                unset($goods_data['status_text']);

                if (count($shop_ids) > 0) {
                    foreach ($shop_ids as $k_shop => $v_shop) {
                        if ($goods_info['shop_id'] == $v_shop) {
                            continue;
                        }
                        //处理新的商品
                        $goods_data['shop_id'] = $v_shop;

                        // print_r($goods_data);die;
                        $new_goods = $this->model->insert($goods_data);


                        if (empty($new_goods)) {
                            Db::rollback();
                            $this->error('操作失败！请稍后重试');
                        }

                        $new_consumable_id = $this->model->getLastInsID();

                        //保存商品铺设记录
                        $insert_data = [];
                        $insert_data['shop_id'] = $v_shop;
                        $insert_data['consumable_id'] = $consumable_id;
                        $insert_data['new_consumable_id'] = $new_consumable_id;
                        $insert_data['createtime'] = time();
                        $insert_res = $this->consumable_shop_model->insert($insert_data);
                        if (empty($insert_res)) {
                            Db::rollback();
                            $this->error('操作失败！请稍后重试');
                        }
                    }
                }

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }
        $this->error(__('You have no permission', ''));
    }
    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

}
